package com.gtfrank.web.servlet.day2;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * @ProjectName: sudacoursetrainging
 * @ClassName: LogerIPServlet
 * @PackageName:com.gtfrank.web.servlet.day2
 * @Description: 实现初始化参数
 * @Author: frank
 * @Date: 2021/4/28 14:03
 * @Version v1.0
 */
@WebServlet(value = "/day2/LogerIPServlet")
public class LogerIPServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html lang=\"en\">");
        out.println("<head>");
        out.println("    <meta charset=\"UTF-8\">");
        out.println("    <title>Title</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("    <h2 align=\"center\">记录访问服务器客户端的IP地址</h2>");
        out.println("    <hr>");
        out.println("    <center>");
        //怎么获得客户端的IP地址
       /* String ip1 = req.getRequestURI();
        StringBuffer ip2 = req.getRequestURL();
        String ip3 = req.getServletPath();
        String ip4 = req.getLocalAddr();*/
        String ip = req.getRemoteAddr();
       // System.out.println(ip1+":"+ip2+":"+ip3+":"+ip4+":"+ip5);
        //把ip地址写到D盘根目录下
        PrintWriter printWriter = new PrintWriter(new FileOutputStream(new File("d:\\ip.txt"),true));
        printWriter.print(new Date());
        printWriter.println(ip);
        out.println("        你的IP为"+ip+"已经被记录！！");
        out.println("    </center>");
        out.println("</body>");
        out.println("</html>");
        printWriter.flush();;
        printWriter.close();
        out.flush();
        out.close();
    }
}
